<template>
  <ele-modal
    v-model="visible"
    :width="1200"
    title="选择商品"
    class="select-product"
    destroy-on-close
    :show-close="false"
    resizable
    :modal="modal"
  >
    <template #header>
      <div class="flex-ba">
        <div class="">
          选择商品
        </div>
        <div class="flex-a">
          <el-checkbox v-model="modal" label="背景遮罩层" border />
          <el-divider class="mx-20px" direction="vertical" />
          <el-button @click="visible = false">
            取消
          </el-button>
          <el-button type="primary" :loading="loading" @click="save">
            确定选中商品
          </el-button>
        </div>
      </div>
    </template>
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      v-model:selections="selections"
      height="60vh"
      row-key="product_id"
      :columns="columns"
      :datasource="datasource"
      :show-overflow-tooltip="true"
      highlight-current-row
      cache-key="SelectProductTable"
      :loadOnCreated="visible"
      @row-click="toggleRowSelection"
    >
      <template #toolbar>
        <PageSearch :locationTree="locationTree" @search="reload" />
      </template>
      <template #multi_unit="{ row }">
        <div v-if="row.multi_unit_status === 1" class="flex-c">
          <template v-for="(item, i) in row.multi_unit" :key="i">
            <div v-if="i">、</div>
            <div :class="i ? '' : 'font-semibold text-primary'">{{ item.unit }}</div>
          </template>
        </div>
        <div v-else>
          {{ row.unit }}
        </div>
      </template>
      <template #price="{ row }">
        <div v-if="!selectable(row)">-</div>
        <el-input
          v-else-if="props.editPrice"
          v-model="row.price"
          size="small"
          :input-style="{ textAlign: 'center' }"
          placeholder="价格"
          @input="row.price = priceInput(row.price)"
          @click.stop
        />
        <div v-else>{{ row.cost_price }}</div>
      </template>
      <!-- <template #num="{ row }">
        <el-input v-model="row.num"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" size="small"
          :input-style="{ textAlign: 'center' }" placeholder="数量" @click.stop>
          <template #suffix>{{ row.unit }}</template>
        </el-input>
      </template> -->

      <template #num="{ row }">
        <div v-if="!selectable(row)">-</div>
        <div v-else class="flex-a" @click.stop>
          <el-space>
            <el-form-item v-for="(item, i) in row.multi_unit" :key="i" :label-width="0" class="mb-0!">
              <el-input
                v-model="item.num"
                class="w-80px!"
                placeholder="数量"
                size="small"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                @input="checkNum(row)"
                @blur="deCheckNum(row)"
              >
                <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
              </el-input>
            </el-form-item>
          </el-space>
          <div v-if="row.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
            = {{ totalUnit(row.multi_unit) }}{{ row.unit }}
          </div>
        </div>
      </template>
      <template #action="{ row }">
        <div v-if="!selectable(row)">-</div>
        <el-link
          v-else
          type="primary"
          :disabled="totalUnit(row.multi_unit) > 0 ? false : true"
          underline="never"
          @click.stop="saveRow(row)"
        >
          添加
        </el-link>
      </template>
    </ele-pro-table>
  </ele-modal>
</template>

<script setup>
import { listProduct } from '@/api/common'
import { useDebounceFn } from '@vueuse/core'
import { toTree } from 'ele-admin-plus/es'
import PageSearch from './search.vue'

const props = defineProps({
  /** 修改回显的数据 */
  where: {
    type: Object,
    default: () => { },
  },
  selecteds: {
    type: Array,
    default: () => [],
  },
  decimal: {
    type: Number,
    default: 2,
  },
  inStock: Boolean,
  showPirce: {
    type: Boolean,
    default: true,
  },
  editPrice: Boolean,
  editNum: {
    type: Boolean,
    default: true,
  },
  queryLoc: Boolean,
})

const emit = defineEmits(['done'])

const visible = defineModel()

const tableRef = ref(null)
const { totalUnit } = utils
// 是否需要遮罩层
const modal = ref(true)

const loading = ref(false)

/** 表格选中数据 */
const selections = ref([])
const product = ref([])

const locationTree = ref([])

watch(() => props.where.warehouse_id, (val) => {
  if (val && props.queryLoc) {
    utils.get('common/wlList', { warehouse_id: val, level: 2 }).then((res) => {
      locationTree.value = toTree({
        data: res.data,
        idField: 'id',
        parentIdField: 'pid',
      })
    })
  }
}, { immediate: true })

const columns = computed(() => {
  const arr = [
    {
      type: 'selection',
      columnKey: 'selection',
      width: 50,
      align: 'center',
      fixed: 'left',
      reserveSelection: true,
      selectable,
    },
    {
      type: 'index',
      columnKey: 'index',
      label: '序',
      width: 50,
      align: 'center',
      fixed: 'left',
    },
    {
      prop: 'name',
      label: '商品名称',
      minWidth: 160,
      showOverflowTooltip: false,
    },
    {
      prop: 'code',
      label: '商品编码',
      width: 140,
      align: 'center',
    },
  ]
  arr.push(
    {
      prop: 'unit',
      label: '主单位',
      align: 'center',
    },
    {
      prop: 'stock',
      label: '仓库库存',
      align: 'center',
      formatter: row => typeof row.warehouse_stock !== 'undefined' ? row.warehouse_stock : row.stock,
    },
  )
  if (props.where.is_location === 1) {
    arr.push({
      prop: 'location',
      label: '库位',
      formatter: row => row.location?.length ? row.location.map(v => v.name).toString() : '-',
      width: 160,
      align: 'center',
    })
  }
  // arr.push({
  //   prop: 'unit',
  //   label: '辅助单位',
  //   width: 140,
  //   align: 'center',
  //   showOverflowTooltip: true,
  //   formatter: row => row.multi_unit_status === 1 ? row.multi_unit?.map(v => v.unit).filter(d => d !== row.unit).join('、') : '-',
  // })
  if (props.editNum) {
    arr.push(
      {
        prop: 'num',
        label: '数量',
        align: 'center',
        slot: 'num',
        width: Math.max(...product.value.map(v => v.multi_unit?.length), 1) * 100 + 40,
      },
      {
        columnKey: 'action',
        label: '操作',
        align: 'center',
        slot: 'action',
        fixed: 'right',
        width: 75,
      },
    )
  }
  if (props.showPirce || props.editPrice) {
    arr.push({
      prop: 'cost_price',
      label: '商品价格',
      align: 'center',
      slot: 'price',
      minWidth: 100,
    })
  }

  return arr
})

function toggleRowSelection(row) {
  if (selectable(row))
    tableRef.value.toggleRowSelection(row, !selections.value.some(v => v.product_id === row.product_id))
}

function selectable(row) {
  return props.inStock && row.stock <= 0 ? false : !props.selecteds.some(v => v.product_id === row.product_id)
}

function priceInput(value) {
  const str = `^\\D*([0-9]\\d*\\.?\\d{0,${props.decimal}})?.*$`
  const reg = new RegExp(str, 'g')
  return value.replace(/[^\d.]/g, '').replace(reg, '$1')
}

/** 表格数据源 */
async function datasource({ page, limit, where, orders }) {
  const res = await listProduct({ ...where, ...orders, ...props.where, page, limit })
  res.data.forEach((v) => {
    v.product_id = v.id
    v.product_name = v.name
    v.product_code = v.code
    v.product_bar_code = v.bar_code
    if (props.editPrice) {
      // v.price = v.cost_price
      v.price = undefined
    }
    v.multi_unit = v.unit_list.map(d => ({ ...d, num: '' }))
  })
  if (where.keyword && res.data.length === 1) {
    toggleRowSelection(res.data[0])
  }
  product.value = res.data
  return res
}

/** 搜索 */
function reload(where) {
  selections.value = []
  tableRef.value?.reload?.({ page: 1, where })
}

async function save() {
  // loading.value = true
  // await utils.sleep(500)
  // loading.value = false
  emit('done', selections.value)
  visible.value = false
  selections.value = []
}

function saveRow(row) {
  tableRef.value.toggleRowSelection(row, false)
  emit('done', [], utils.cloneDeep(row))
}

const checkNum = useDebounceFn(deCheckNum, 500)

function deCheckNum(row) {
  const bool = utils.totalUnit(row.multi_unit) > 0
  if (bool && !selections.value.some(v => v.product_id === row.product_id)) {
    tableRef.value.toggleRowSelection(row, true)
  }
  else if (!bool && selections.value.some(v => v.product_id === row.product_id)) {
    tableRef.value.toggleRowSelection(row, false)
  }
}
</script>

<style lang="scss">
.select-product .ele-modal-body {
  padding: 10px 20px 15px;
}
</style>
